<!DocType html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>recv real log</title>
    <link rel="shortcut icon" href="./favicon.ico">
    <script src="./vue.js"></script>
</head>
<body>

<div>
</div>

<div id="logger" style="margin-left: 100px">
    <br>
    <label>{{tipConnected}}</label>
    <button style="margin-left: 20px;width:100px;height:40px" v-on:click="startAction">{{btnTitle}}</button>
    <button style="margin-left: 20px;width:100px;height:40px" v-on:click="clearLogger">clear</button>
    <br>
    <br>
    <ol>
        <li v-for="item in items">
            {{item}}
        </li>
    </ol>
</div>


<script>

    let url = window.location.origin.replace("http", "ws") + "/requestLog";
    let ws = null;

    let logger = new Vue({
        el: '#logger',
        data: {
            connected: false,
            tipConnected: '未连接',
            items: [
                'recv logger'
            ]
        },
        computed:{
            btnTitle:function () {

                return this.connected ? '关闭连接':'开始连接';
            }
        },
        methods: {
            addlogger: function (message) {

                this.items.push(message);
            },
            clearLogger: function () {

                this.items = [];
            },
            startAction:function(){

                if (this.connected)
                    this.stopConnect();
                else
                    this.startConnect();
            },
            startConnect: function () {

                console.log('start');

                if (this.connected)
                    return;

                let vm= this;
                ws = new WebSocket(url);
                ws.onopen = function (event) {
                    console.log("ws opened");

                    vm.tipConnected = '连接成功';
                    vm.connected = true;
                }
                ws.onclose = function (event) {
                    console.log("ws close:", event.data);

                    vm.tipConnected = '连接关闭';
                    vm.connected = false;
                }
                ws.onmessage = function (event) {
                    let message = event.data;

                    vm.addlogger(message);
                }
                ws.onerror = function (event) {
                    console.log("ws error:", event.data);

                    this.tipConnected = '连接错误';

                    vm.connected = false;
                }
            },
            stopConnect:function () {

                console.log('stop');

                if (this.connected){
                    ws.close();
                }
                this.connected = false;
                this.tipConnected = '未连接';
            }

        }
    })

</script>


</body>
</html>
